"use strict";
const { ConcatSource } = require("webpack-sources");

class AppendPlugin{
  constructor(name,append){
    this.filename = `${name}/index.js`;
    this.appendString = append;
  }
  apply(compiler) {
    compiler.hooks.compilation.tap("AppendPlugin", compilation => {
			compilation.hooks.optimizeChunkAssets.tap("AppendPlugin", chunks => {
				for (const chunk of chunks) {
					for (const file of chunk.files) {
            // console.info(file,this.filename);
            if(file.indexOf(this.filename)==-1)continue;
            compilation.assets[file] = new ConcatSource(
              compilation.assets[file],
							"\n",
              this.appendString
            );
					}
				}
			});
		});
  }
}
module.exports.AppendPlugin = AppendPlugin;
class OverPlugin{
  constructor(overCb,name){
    this.overCb = overCb;
    this.name = name;
  }
  apply(compiler){
    compiler.hooks.done.tapAsync('OverPlugin',stats=>{
      if(!stats.hasErrors()&&this.overCb){
        console.log(`\n${this.name}正确打包完成`);
        this.overCb();
      }else{
        stats.compilation.errors.forEach(n=>{
          console.error(n.message);
        })
        throw new Error("编辑失败");
      }
    })
  }
}

module.exports.OverPlugin = OverPlugin;